from django.forms import ModelForm, PasswordInput
from django.shortcuts import render, redirect
from emp.models import EmpInfo
from emp.utils.pagination import PageNumberPagination


# MyForm
class EmpAddForm(ModelForm):
    class Meta:
        model = EmpInfo
        fields = ['name', 'password', 'age', 'account', 'entry_date', 'gender', 'dept']
        widgets = {
            'password': PasswordInput(),
        }
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            field.widget.attrs = {'class' : 'form-control', "placeholder" : field.label}

# 展示员工信息
def emp_show(request):
    # for i in range(100,200):
    #     EmpInfo.objects.create(name="test" + str(i), password="12", age=10, account=0, entry_date="2000-09-28", gender=1,
    #                             dept=DeptInfo.objects.get(id=1))
    if request.GET.get('del_id'):
        dept_id = request.GET.get('del_id')
        EmpInfo.objects.filter(id=dept_id).delete()
        if request.GET.get("search"):
            search = request.GET.get('search')
            return redirect('/emp?search=' + search)
        else:
            return redirect('/emp/')

    if request.GET.get("search"):
        search = request.GET.get('search')
        emp_list = EmpInfo.objects.filter(name__icontains=search).order_by('id')
    else:
        search = ""
        emp_list = EmpInfo.objects.all()

    if request.GET.get("page"):
        page = int(request.GET.get("page"))
    else:
        page = 1
    p = PageNumberPagination(emp_list, page)

    return render(request, "emp_show.html",
                  {"emp_list": p.list_show, 'search': search,
                   "page_range": p.page_range,"curr_page": page,
                   "last": p.page_last, "next": p.page_next,
                   "page_sum": p.page_sum})

# 添加员工信息
def emp_add(request):
    if request.method == "POST":
        form = EmpAddForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('/emp/')
        else:
            print(form.errors)
        return render(request, 'emp_add.html', {'form': form})
    elif request.method == "GET":
        form = EmpAddForm()
        return render(request, 'emp_add.html', {'form': form})

# 修改员工信息
def emp_update(request):
    emp_id = request.GET.get("upd_id")
    emp = EmpInfo.objects.get(id=emp_id)
    if request.method == "POST":
        form = EmpAddForm(data=request.POST, instance=emp)
        if form.is_valid():
            form.save()
            return redirect('/emp/')
        else:
            print(form.errors)
            return render(request, 'emp_update.html', {'form': form})
    elif request.method == "GET":
        form = EmpAddForm(instance=emp)
        return render(request, 'emp_update.html', {"udp_id": emp_id, "form": form})